package com.define.ssh.action.admin;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;

import com.define.ssh.model.Role;
import com.define.ssh.model.UserInfo;
import com.define.ssh.service.RoleService;
import com.define.ssh.service.UserInfoService;
import com.define.ssh.util.SystemUtil;

/**
 * 用户操作类
 * 
 * @author hcy
 * 
 */
@ParentPackage("admin")
public class UserInfoAction extends BaseAdminAction {

	/** 页面传递参数过来 */
	protected int pageSize;
	protected int pageNum;

	@Resource(name = "userInfoServiceImpl")
	private UserInfoService userInfoService;
	@Resource(name = "roleServiceImpl")
	private RoleService roleService;

	private UserInfo userInfo;
	private String treeData;
	private Long pid = 0L;
	private Long cid = 0L;
	private String name;
	private File img;
	private String imgFileName;
	private Long role_id;

	private String newPwd;
	private String newPwd_q;
	private String oldPwd;

	/**
	 * 列表页
	 * 
	 * @return
	 * @throws Exception
	 */
	public String list() {
		final UserInfo userInfo = (UserInfo) super.getRequest().getSession()
				.getAttribute(SystemUtil.USERINFO);
		final HashMap<String, Object> searchMap = new HashMap<String, Object>();
		// if(!"1".equals(userInfo.getRole().getId())){//非管理员
		// searchMap.put("userLogin", userInfo.getLogin());
		// }
		pager.setSearchMap(searchMap);
		pager = userInfoService.findPager(pager);
		return LIST;
	}

	/**
	 * 选择用户
	 * 
	 * @return
	 * @throws Exception
	 */
	public String select() {

		final UserInfo userInfo = (UserInfo) super.getRequest().getSession()
				.getAttribute(SystemUtil.USERINFO);

		final HashMap<String, Object> searchMap = new HashMap<String, Object>();
		if (pid != 0) {
			searchMap.put("zyOrganization.id", pid);
		}
		if (cid != 0) {
			searchMap.put("zyOrganization.id", cid);
		}
		if (org.apache.commons.lang3.StringUtils.isNotEmpty(name)) {
			searchMap.put("userName", name);
		}
		/*
		 * if(!"1".equals(userInfo.getRole().getId())){//非管理员
		 * searchMap.put("userLogin", userInfo.getLogin()); }
		 * if(province!=null&&!"".equals(province)){
		 * searchMap.put("provinceCode", province);
		 * super.getRequest().setAttribute("province", province); }
		 * if(cityCode!=null&&!"".equals(cityCode)){ searchMap.put("cityCode",
		 * cityCode); super.getRequest().setAttribute("cityCode", cityCode); }
		 * if(areaCode!=null&&!"".equals(areaCode)){ searchMap.put("areaCode",
		 * areaCode); super.getRequest().setAttribute("areaCode", areaCode); }
		 */
		pager.setSearchMap(searchMap);
		pager = userInfoService.findPager(pager);
		return "select";
	}

	// 删除
	public String delete() {
		final StringBuffer logInfoStringBuffer = new StringBuffer("删除管理员: ");
		for (final Long id : ids) {
			final UserInfo ss = userInfoService.load(id);
			userInfoService.delete(ss);
		}
		logInfo = logInfoStringBuffer.toString();
		return ajax(Status.success, "删除成功!");
	}

	// 更改状态是否有效无效
	public String updateStatus() {
		final StringBuffer logInfoStringBuffer = new StringBuffer("更改状态");
		final String id = super.getRequest().getParameter("id");
		final String isvalid = super.getRequest().getParameter("isvalid");
		final UserInfo ss = userInfoService.load(Long.valueOf(id));
		// ss.setIsvalid(Integer.parseInt(isvalid));
		userInfoService.update(ss);
		logInfo = logInfoStringBuffer.toString();
		return ajax(Status.success, "更改状态成功!");
	}

	// 添加
	public String add() {

		final UserInfo userInfo = (UserInfo) super.getRequest().getSession()
				.getAttribute(SystemUtil.USERINFO);
		// 设置查询参数
		List<Role> roleList = null;
		if (!"1".equals(userInfo.getRole().getId().toString())) {// 非管理员
			roleList = new ArrayList<Role>();
			roleList.add(userInfo.getRole());
		} else {
			final HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("isvalid", "0");
			roleList = roleService.getAllListByParameter(map);
		}
		super.getRequest().setAttribute("roleList", roleList);
		// 查询省份
		final HashMap<String, String> map1 = new HashMap<String, String>();
		return INPUT;
	}

	// 编辑
	public String edit() {

		// 设置查询参数
		List<Role> roleList = null;
		final HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("isvalid", "0");
		roleList = roleService.getAllListByParameter(map);
		super.getRequest().setAttribute("roleList", roleList);

		userInfo = userInfoService.load(id);
		return INPUT;
	}

	public String check() {
		// if (userInfoService.isExistByLogin(userInfo.getLogin())) {
		// return ajax(Status.error, "用户名已存在!");
		// }
		return ajax(Status.success, "ok");
	}

	// 保存
	public String save() {
		// if (userInfoService.isExistByLogin(userInfo.getLogin())) {
		// return ajax(Status.error, "用户名已存在!");
		// }
		/*
		 * if(userInfo.getPhone()!=null&&!"".equals(userInfo.getPhone().trim())){
		 * boolean flg = StringUtil.checkMobile(userInfo.getPhone().trim());
		 * if(!flg){ return ajax(Status.error, "手机号码格式错误!"); } }
		 * if(userInfo.getEmail
		 * ()!=null&&!"".equals(userInfo.getEmail().trim())){ boolean flg =
		 * StringUtil.checkEmail(userInfo.getEmail().trim()); if(!flg){ return
		 * ajax(Status.error, "电子邮箱格式错误！"); } } SimpleDateFormat sf = new
		 * SimpleDateFormat("MM-dd");
		 * if(userInfo.getBirthday()!=null&&!"".equals
		 * (userInfo.getBirthday().toString())){
		 * userInfo.setBirthdayStr(sf.format(userInfo.getBirthday())); }
		 */
		final Role role = roleService.load(role_id);
		userInfo.setRole(role);
		// userInfo.setCreateDate(new Date());
		// userInfo.setUserLogin(super.getRequest().getSession().getAttribute(SystemUtil.USERLOGIN)+"");
		final String pwd = newPwd;
		final String passwordMd5 = DigestUtils.md5Hex(pwd).toUpperCase();
		// userInfo.setPwd(passwordMd5);

		final long temp = userInfoService.save(userInfo);
		if (img != null) {
			try {
				final String signature = this.saveimg(img, imgFileName, temp
						+ "");
				if (org.apache.commons.lang3.StringUtils.isNotEmpty(signature)) {
					final UserInfo ui = userInfoService.get(temp);
					// ui.setSignature(signature);
					userInfoService.update(ui);
				}
			} catch (final Exception e) {
				e.printStackTrace();
			}
		}

		logInfo = "添加用户: " + userInfo.getName();
		return list();
	}

	// 更新
	public String update() {
		/*
		 * if(userInfo.getPhone()!=null&&!"".equals(userInfo.getPhone().trim())){
		 * boolean flg = StringUtil.checkMobile(userInfo.getPhone().trim());
		 * if(!flg){ return ajax(Status.error, "手机号码格式错误!"); } }
		 * if(userInfo.getEmail
		 * ()!=null&&!"".equals(userInfo.getEmail().trim())){ boolean flg =
		 * StringUtil.checkEmail(userInfo.getEmail().trim()); if(!flg){ return
		 * ajax(Status.error, "电子邮箱格式错误！"); } }
		 */
		final UserInfo persistent = userInfoService.load(id);
		final String pwd = newPwd;
		if (StringUtils.isNotEmpty(pwd)) {
			final String passwordMd5 = DigestUtils.md5Hex(pwd).toUpperCase();
			persistent.setPassword(passwordMd5);
		}
		// persistent.setModifyDate(new Date());
		// persistent.setUserLogin(super.getRequest().getSession().getAttribute(SystemUtil.USERLOGIN)+"");
		persistent.setSex(userInfo.getSex());
		persistent.setEmail(userInfo.getEmail());
		// persistent.setLogin(userInfo.getLogin());
		// persistent.setProvinceCode(userInfo.getProvinceCode());
		// persistent.setCityCode(userInfo.getCityCode());
		// persistent.setAreaCode(userInfo.getAreaCode());
		// persistent.setIfwww(userInfo.getIfwww());

		final Role role = roleService.load(role_id);
		persistent.setRole(role);
		// persistent.setUserName(userInfo.getUserName());
		persistent.setPhone(userInfo.getPhone());
		// persistent.setIsvalid(userInfo.getIsvalid());
		// persistent.setBirthday(userInfo.getBirthday());
		// persistent.setIfmanage(userInfo.getIfmanage());
		final SimpleDateFormat sf = new SimpleDateFormat("MM-dd");
		// if(userInfo.getBirthday()!=null&&!"".equals(userInfo.getBirthday().toString())){
		// persistent.setBirthdayStr(sf.format(userInfo.getBirthday()));
		// }
		if (img != null) {
			try {
				final String signature = this
						.saveimg(img, imgFileName, id + "");
				if (org.apache.commons.lang3.StringUtils.isNotEmpty(signature)) {
					// persistent.setSignature(signature);
				}
			} catch (final Exception e) {
				e.printStackTrace();
			}
		}

		userInfoService.update(persistent);
		logInfo = "编辑用户: " + userInfo.getName();
		return list();
	}

	private String saveimg(File img, String imgFileName, String userid)
			throws IOException {
		String re = "";
		final String realpath = ServletActionContext.getServletContext()
				.getRealPath("/upload/signature");

		if (img != null && imgFileName != null) {
			imgFileName = imgFileName.replace(
					imgFileName.substring(0, imgFileName.indexOf(".")), userid);
			final File savefile = new File(new File(realpath), imgFileName);
			if (!savefile.getParentFile().exists())
				savefile.getParentFile().mkdirs();
			FileUtils.copyFile(img, savefile);
			re = "/upload/signature/" + imgFileName;
		}
		return re;
	}

	// 进入修改密码
	public String toupdatepwd() {
		// userInfo = userInfoService.load(id);
		return "updatepwd";
	}

	// 修改密码
	public String updatepwd() {

		final UserInfo userInfo = (UserInfo) super.getRequest().getSession()
				.getAttribute(SystemUtil.USERINFO);
		// 验证旧密码是否正确
		final String oldmd5 = DigestUtils.md5Hex(oldPwd).toUpperCase();

		final UserInfo ui = userInfoService.load(userInfo.getId());

		if (ui.getPassword().equals(oldmd5)) {
			ui.setPassword(DigestUtils.md5Hex(newPwd).toUpperCase());
			userInfoService.update(ui);
		} else {
			return ajax(Status.error, "旧密码不正确");
		}
		return ajax(Status.success, "修改成功,请重新登陆!");
	}

	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	public String getTreeData() {
		return treeData;
	}

	public void setTreeData(String treeData) {
		this.treeData = treeData;
	}

	public Long getPid() {
		return pid;
	}

	public void setPid(Long pid) {
		this.pid = pid;
	}

	public Long getCid() {
		return cid;
	}

	public void setCid(Long cid) {
		this.cid = cid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public File getImg() {
		return img;
	}

	public void setImg(File img) {
		this.img = img;
	}

	public String getImgFileName() {
		return imgFileName;
	}

	public void setImgFileName(String imgFileName) {
		this.imgFileName = imgFileName;
	}

	public Long getRole_id() {
		return role_id;
	}

	public void setRole_id(Long role_id) {
		this.role_id = role_id;
	}

	public String getNewPwd() {
		return newPwd;
	}

	public void setNewPwd(String newPwd) {
		this.newPwd = newPwd;
	}

	public String getNewPwd_q() {
		return newPwd_q;
	}

	public void setNewPwd_q(String newPwd_q) {
		this.newPwd_q = newPwd_q;
	}

	public String getOldPwd() {
		return oldPwd;
	}

	public void setOldPwd(String oldPwd) {
		this.oldPwd = oldPwd;
	}

}
